<?php
namespace App\Model\Backstage;
use App\Model\Base;
use Illuminate\Support\Facades\DB;

/**
 * Class MoveRuleStatus
 * @package App\Model\Backstage
 * 公司房客自动转移规则验证是否更新model
 */
class MoveRuleStatus extends Base
{
    protected $table = 'move_rule_status';
    public $primaryKey = 's_id';
    public $timestamps = false;
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @param MoveRule $moveRule
     * @param RoomInfo $roomInfo
     * @param Customers $customers
     * @return bool|void
     * 查找当前公司自定义规则并按照条件进行更新
     */
    public function getStatus($moveRule, $roomInfo, $customers){
        $return = true;
        $info =  MoveRuleStatus::where('s_b_id', $this->branch_id)->first();
        if(sizeof($info) < 1){
            return false;
        }
        if($info['s_status'] == 0){  //说明公司规则未更新
            $list = $moveRule->updateList();
            if(sizeof($list) < 1){  //如果公司没有设置规则返回成功
                return true;
            }
            DB::beginTransaction();
            try
            {
                foreach($list as $v){
                    if($v->a_move_type == 0 || $v->a_move_type == 2){  //私盘转公盘  取消优质房
                        $roomInfo->updateRuleDisk($v);
                    }elseif($v->a_move_type == 1){  //私客转公客
                        $customers->updateRuleCustomers($v);
                    }
                }
                MoveRuleStatus::where('s_b_id',$this->branch_id)->update([
                    's_status' => 1,
                    's_updated_at' => time()
                ]);
                DB::commit();
                return true;
            }
            catch(Exception $e)
            {
                DB::rollback();
                return false;
            }

        }
        return $return;
    }

    /**
     * @return mixed
     * 将公司更新状态改为未更新
     */
    public static function updateStatus(){
        return MoveRuleStatus::where('s_status',1)->update([
            's_status' => 0,
            's_updated_at' => time()
        ]);
    }

}